<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="单元责任划分"
      :indentSize="30"
      :pagination="false"
      :searchInfo="searchInfo"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
      @fetch-success="onFetchSuccess"
    >
      <template #toolbar>
        <a-button type="primary" @click="onSetDutyButtonClick">设置责任制</a-button>
        <a-button @click="exportData">导出</a-button>
      </template>
      <template #unitname="{ column, record }">
        <a @click="onViewUnitDivisionButtonClick(record)">{{ record.unitname }}</a>
      </template>
      <template #uccd="{ column, record }">
        {{ returnCategoryName(record.uccd, unitCategoryData) }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:eye-outlined',
              label: '查看',
              onClick: onViewUnitDivisionButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <UnitBasicInfoDrawer @register="registerUnitBasicInfo" @success="afterSuccess" />
    <setUnitResponsibilityModal @register="registerSetDutyModal" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref, nextTick, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { EhsUnitTreeTableItemDto } from '/@/api/ehs/model/unitDivisionModel';
  import { useDrawer } from '/@/components/Drawer';
  import { unitDivisionTableColumns, queryUnitConditionFormSchema } from './responsibility.data';
  import { queryUnitCategory } from '/@/api/ehs/unitCategory';
  import * as XLSX from 'xlsx';
  import UnitBasicInfoDrawer from '../unitDivision/UnitBasicInfoDrawer.vue';
  import setUnitResponsibilityModal from './setUnitResponsibilityModal.vue';
  export default defineComponent({
    name: 'dutyIndex',
    components: {
      BasicTable,
      TableAction,
      UnitBasicInfoDrawer,
      setUnitResponsibilityModal,
    },
    setup() {
      const [registerUnitBasicInfo, { openDrawer: openUnitBasicInfoDrawwer }] = useDrawer();
      const [registerSetDutyModal, { openModal: openSetDutyModal }] = useModal();
      const unitCategoryData = ref([]);
      const searchInfo = ref({
        includechilds: true,
        isdept: false,
      });
      const orgcode = ref('');
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const [
        registerTable,
        {
          reload,
          getDataSource,
          getForm,
          expandAll,
          getSelectRows,
          getSelectRowKeys,
          clearSelectedRowKeys,
        },
      ] = useTable({
        api: queryUnitDivision,
        columns: unitDivisionTableColumns,
        canResize: true,
        size: 'small',
        striped: false,
        showTableSetting: true,
        showIndexColumn: false,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        useSearchForm: true,
        formConfig: {
          labelWidth: 80,
          schemas: queryUnitConditionFormSchema,
          showResetButton: false,
        },
        immediate: false,
        beforeFetch: (params) => {
          return {
            ...params,
            flagisvalid: false,
            orgcode: orgcode.value,
          };
        },
        afterFetch: (res) => {
          let tmp = [];
          treeToArray(res).forEach((item) => {
            let value = {
              unitname: item.unitname,
              resdeptname: item.resdeptname,
              resusername: item.resusername,
              resuserphone: item.resuserphone,
              safeusername: item.safeusername,
              safeuserphone: item.safeuserphone,
            };
            tmp.push(value);
          });
          tmp.unshift(['单元', '责任部门', '责任人', '责任人手机号', '安全员', '安全员手机号']);
          ledgerData = tmp.map((item) => {
            return Object.keys(item).map((key) => item[key]);
          });
          return res;
        },
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        rowSelection: { type: 'checkbox' },
        rowKey: 'unitid',
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        clearSelectedRowKeys();
        reload();
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];
        //递归函数 traverse，用于处理单个节点
        function traverse(node) {
          const newNode = { ...node };
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach(traverse);
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      /**
       * 查看基础信息
       */
      function onViewUnitDivisionButtonClick(record: EhsUnitTreeTableItemDto) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元基础信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.unitid,
        };
        openUnitBasicInfoDrawwer(true, propsData);
      }

      function onFetchSuccess() {
        nextTick(expandAll);
      }

      function onSetDutyButtonClick() {
        if (getSelectRowKeys().length == 0) {
          return createMessage.error('请选择要设置的单元');
        }
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '责任机制',
          operateString: '设置',
          ids: getSelectRowKeys(),
          defaultData: getSelectRows()[0], // 获取第一个选中单元信息作为责任信息默认值
          unitData: getDataSource(),
        };
        openSetDutyModal(true, propsData);
      }

      function returnCategoryName(uccd, unitCategory) {
        for (let i = 0; i < unitCategory.length; i++) {
          let a = unitCategory[i];
          if (a.uccd == uccd) {
            return a.ucnm;
          } else {
            if (a.children && a.children.length > 0) {
              let res = returnCategoryName(uccd, a.children);
              if (res) {
                return res;
              }
            }
          }
        }
        return uccd;
      }

      //需要导出的数组数据
      let ledgerData = [];
      // 表格数据导出
      function exportData() {
        const filename = `单元责任机制.xlsx`; //导出文件名
        const worksheet_name = 'Sheet1'; // Excel第一个sheet的名称
        const workbook = XLSX.utils.book_new(); //创建一个新的workbook
        const worksheet = XLSX.utils.aoa_to_sheet(ledgerData);
        console.log(ledgerData, 'ledgerData');
        worksheet['!merges'] = [];
        //列宽设置
        worksheet['!cols'] = [
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
          { width: 30 },
        ];
        //保存数据信息并下载文件
        XLSX.utils.book_append_sheet(workbook, worksheet, worksheet_name); //将数据添加到工作簿
        XLSX.writeFile(workbook, filename); //下载excel文件
      }

      onMounted(() => {
        getUserOrganization(projectCode.value).then((res) => {
          // 请求时需要传入用户的组织编码
          orgcode.value = res?.orgcode;
          reload();
        });
        //  获取枚举类
        queryUnitCategory()
          .then((res) => {
            unitCategoryData.value = res;
            getForm().updateSchema({
              field: 'uccd',
              componentProps: {
                treeData: res,
                fieldNames: { label: 'ucnm', value: 'uccd', children: 'children' },
              },
            });
          })
          .catch((e) => {});
      });

      return {
        searchInfo,
        unitCategoryData,
        onFetchSuccess,
        registerUnitBasicInfo,
        registerSetDutyModal,
        registerTable,
        afterSuccess,
        onViewUnitDivisionButtonClick,
        returnCategoryName,
        onSetDutyButtonClick,
        exportData,
      };
    },
  });
</script>

<style scoped>
  a {
    color: #000000;
  }
</style>
